﻿using Newtonsoft.Json;

namespace Service.Framework.Utils
{
    /// <summary>
    /// Json序列化辅助器
    /// </summary>
    public class JsonSerializeUtil
    {
        public static JsonSerializerSettings DefaulSerializeSetting { get; } = new JsonSerializerSettings()
        {
            DateFormatString = "yyyy-MM-dd HH:mm:ss:fff",
            NullValueHandling = NullValueHandling.Include,
            Formatting = Formatting.Indented,
            //ContractResolver = new DefaultContractResolver(),
            ContractResolver = new CustomContractResolver(),
            //Converters = new List<JsonConverter>() { new StringEnumConverter() },
        };


        public static String SerializeObject(Object value, Boolean useSetting = true)
        {
            if (useSetting)
            {
                return JsonConvert.SerializeObject(value, DefaulSerializeSetting);
            }
            return JsonConvert.SerializeObject(value);
        }

        public static String SerializeObject(Object value, Formatting formatting)
        {
            return JsonConvert.SerializeObject(value, formatting, DefaulSerializeSetting);
        }

        public static String SerializeObject(Object value, JsonSerializerSettings settings)
        {
            return JsonConvert.SerializeObject(value, settings);
        }


        public static T Deserialize<T>(String json, Boolean useSetting = true)
        {
            if (String.IsNullOrEmpty(json))
            {
                return default(T);
            }
            if (useSetting)
                return JsonConvert.DeserializeObject<T>(json, DefaulSerializeSetting);
            else
                return JsonConvert.DeserializeObject<T>(json);
        }


    }
}
